package com.ww.demo.thread.d3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Run {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        new Thread(() -> runMethod(lock), "thread1").start();
        new Thread(() -> runMethod(lock), "thread2").start();
        new Thread(() -> runMethod(lock), "thread3").start();
        new Thread(() -> runMethod(lock), "thread4").start();

        new Thread(new Runnable(){
            @Override
            public void run() {
                runMethod(lock);
            }
        }, "thread5").start();

        new Thread(() -> runMethod(lock, 0), "thread6").start();
        new Thread(() -> runMethod(lock, 5000), "thread7").start();
        new Thread(() -> runMethod(lock, 1000), "thread8").start();
        new Thread(() -> runMethod(lock, 5000), "thread9").start();
        new Thread(() -> runMethod(lock, 1000), "thread10").start();

    }

    private static void runMethod(Lock lock){
        lock.lock();
        for (int i = 1; i <= 5; i++){
            System.out.println("Thread name:" + Thread.currentThread().getName() + "(" + i +")");
        }
        System.out.println();
        lock.unlock();
    }

    private static void runMethod(Lock lock, long sleepTime){
        lock.lock();
        try {
            Thread.sleep(sleepTime);
            System.out.println("Thread name:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}
